package com.novellotus.iov.carvice.anim;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.FrameLayout;

/**
 * Created by wpm on 2017/4/1.
 */

public class EnterAnimLayout extends FrameLayout {
    private Anim anim;
    private long startTime = 0;//开始时间
    private boolean mIsAnimaionRun = false;
    private boolean mIsVisibleAtFirst = true;
    private float t1;
    private int n;

    public EnterAnimLayout(Context context) {
        super(context);
    }

    public EnterAnimLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EnterAnimLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    /**
     * 设置动画
     */
    public void setAnim(Anim anim) {
        this.anim = anim;
    }

    public long getStartTime() {
        return startTime;
    }

    public void setStartTime(long startTime) {
        this.startTime = startTime;
    }

    public boolean ismIsAnimaionRun() {
        return mIsAnimaionRun;
    }

    /**
     * 标记动画是否在运行
     */
    public void setmIsAnimaionRun(boolean mIsAnimaionRun) {
        this.mIsAnimaionRun = mIsAnimaionRun;
        if(mIsAnimaionRun){
            t1=0;
            n=0;
        }
    }


    @Override
    protected void dispatchDraw(Canvas canvas) {
        if (mIsVisibleAtFirst && !mIsAnimaionRun) {
            super.dispatchDraw(canvas);
            return;
        }
        if (!mIsVisibleAtFirst && !mIsAnimaionRun) {
            return;
        }

        long currentTime = System.currentTimeMillis();
        float rate = ((float) (currentTime - startTime)) / anim.totalPaintTime;
        if(t1==0){
            t1=rate;
        }
        rate = rate > 1 ? 1 : rate;
        if(t1<rate&&rate<1){
            rate= rate+n*(n-1)*0.00008f;
         //   Log.e("t--",rate+"");
        }
        anim.handleCanvas(canvas, rate);

        super.dispatchDraw(canvas);
        //当动画shi'jian
        if (rate < 1) {
            //递归
         //   Log.e("tag","draw");
            n++;
            invalidate();
        } else {
            mIsAnimaionRun = false;
            mIsVisibleAtFirst = true;
        }
    }


    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        //正在播放动画时点击才拦截
        if (ev.getAction() == MotionEvent.ACTION_DOWN && mIsAnimaionRun) {
            mIsAnimaionRun = true;
            return true;
        }
        return super.onInterceptTouchEvent(ev);
    }
}
